// pages/job-detail/job-detail.js
Page({
  data: {
    jobId: null,
    job: null,
    loading: true,
    hasApplied: false,
    applicationId: null,
    applicationStatus: null,
    showApplyModal: false,
    applyMessage: '',
    // 申请表单数据
    applyForm: {
      realName: '',
      phone: '',
      idCard: '',
      address: ''
    }
  },

  onLoad(options) {
    const jobId = options.id;
    if (jobId) {
      this.setData({ jobId });
      this.loadJobDetail();
      this.checkApplicationStatus();
    } else {
      wx.showToast({
        title: '岗位不存在',
        icon: 'none'
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
    }
  },

  // 加载岗位详情
  loadJobDetail() {
    wx.request({
      url: `http://localhost:8080/api/jobs/${this.data.jobId}`,
      method: 'GET',
      success: (res) => {
        if (res.data.success) {
          this.setData({
            job: res.data.data,
            loading: false
          });
        } else {
          this.showError('岗位不存在');
        }
      },
      fail: () => {
        // 模拟数据
        const mockJob = {
          id: this.data.jobId,
          title: '前端开发工程师',
          company: '某科技公司',
          jobType: 'FULL_TIME',
          minSalary: 8000,
          maxSalary: 15000,
          salaryType: 'MONTHLY',
          location: '北京市朝阳区中关村软件园',
          description: '负责公司前端项目开发，参与产品需求分析，设计并实现用户界面，优化用户体验。要求熟悉React、Vue等主流前端框架，具备良好的编程习惯和团队协作能力。',
          skillRequirements: 'React, Vue, JavaScript, HTML5, CSS3, Node.js',
          workTime: '周一至周五 9:00-18:00',
          requiredWorkers: 2,
          matchedWorkers: 1,
          status: 'PUBLISHED',
          publishTime: '2024-01-10 10:00:00',
          expireTime: '2024-02-10 10:00:00',
          employer: {
            id: 1,
            companyName: '某科技公司',
            contactPhone: '010-12345678',
            businessAddress: '北京市朝阳区中关村软件园A座'
          }
        };
        
        this.setData({
          job: mockJob,
          loading: false
        });
      }
    });
  },

  // 检查申请状态
  checkApplicationStatus() {
    const token = wx.getStorageSync('token');
    if (!token) return;

    wx.request({
      url: `http://localhost:8080/api/user/applications/job/${this.data.jobId}`,
      method: 'GET',
      header: {
        'Authorization': `Bearer ${token}`
      },
      success: (res) => {
        if (res.data.success && res.data.data) {
          this.setData({
            hasApplied: true,
            applicationId: res.data.data.id,
            applicationStatus: res.data.data.status
          });
        }
      },
      fail: () => {
        // 模拟已申请状态
        this.setData({
          hasApplied: false
        });
      }
    });
  },

  // 显示申请弹窗
  showApplyModal() {
    const token = wx.getStorageSync('token');
    if (!token) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      setTimeout(() => {
        wx.switchTab({
          url: '/pages/profile/profile'
        });
      }, 1500);
      return;
    }

    // 获取用户信息预填表单
    const userInfo = wx.getStorageSync('userInfo');
    if (userInfo) {
      this.setData({
        'applyForm.realName': userInfo.realName || '',
        'applyForm.phone': userInfo.phone || '',
        'applyForm.idCard': userInfo.idCard || ''
      });
    }

    this.setData({
      showApplyModal: true,
      applyMessage: ''
    });
  },

  // 隐藏申请弹窗
  hideApplyModal() {
    this.setData({
      showApplyModal: false
    });
  },

  // 申请消息输入
  onApplyMessageInput(e) {
    this.setData({
      applyMessage: e.detail.value
    });
  },

  // 申请表单输入
  onApplyFormInput(e) {
    const { field } = e.currentTarget.dataset;
    this.setData({
      [`applyForm.${field}`]: e.detail.value
    });
  },

  // 提交申请
  submitApplication() {
    // 验证必填字段
    const { realName, phone, idCard } = this.data.applyForm;
    if (!realName.trim()) {
      wx.showToast({
        title: '请输入姓名',
        icon: 'none'
      });
      return;
    }
    if (!phone.trim()) {
      wx.showToast({
        title: '请输入手机号',
        icon: 'none'
      });
      return;
    }
    if (!idCard.trim()) {
      wx.showToast({
        title: '请输入身份证号',
        icon: 'none'
      });
      return;
    }
    if (!this.data.applyMessage.trim()) {
      wx.showToast({
        title: '请输入申请理由',
        icon: 'none'
      });
      return;
    }

    const token = wx.getStorageSync('token');

    wx.request({
      url: 'http://localhost:8080/api/user/applications',
      method: 'POST',
      header: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      },
      data: {
        jobId: this.data.jobId,
        message: this.data.applyMessage,
        realName: realName.trim(),
        phone: phone.trim(),
        idCard: idCard.trim(),
        address: this.data.applyForm.address.trim()
      },
      success: (res) => {
        if (res.data.success) {
          wx.showToast({
            title: '申请成功',
            icon: 'success'
          });
          this.setData({
            hasApplied: true,
            applicationId: res.data.data.id,
            applicationStatus: 'PENDING',
            showApplyModal: false
          });
        } else {
          wx.showToast({
            title: res.data.message || '申请失败',
            icon: 'none'
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: '申请成功',
          icon: 'success'
        });
        this.setData({
          hasApplied: true,
          applicationId: Date.now(),
          applicationStatus: 'PENDING',
          showApplyModal: false
        });
      }
    });
  },

  // 撤销申请
  cancelApplication() {
    wx.showModal({
      title: '确认撤销',
      content: '确定要撤销申请吗？',
      success: (res) => {
        if (res.confirm) {
          this.performCancelApplication();
        }
      }
    });
  },

  // 执行撤销申请
  performCancelApplication() {
    const token = wx.getStorageSync('token');

    wx.request({
      url: `http://localhost:8080/api/user/applications/${this.data.applicationId}/cancel`,
      method: 'PUT',
      header: {
        'Authorization': `Bearer ${token}`
      },
      success: (res) => {
        if (res.data.success) {
          wx.showToast({
            title: '申请已撤销',
            icon: 'success'
          });
          this.setData({
            hasApplied: false,
            applicationId: null,
            applicationStatus: null
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: '申请已撤销',
          icon: 'success'
        });
        this.setData({
          hasApplied: false,
          applicationId: null,
          applicationStatus: null
        });
      }
    });
  },

  // 联系雇主
  contactEmployer() {
    if (!this.data.job || !this.data.job.employer) {
      wx.showToast({
        title: '无法获取联系方式',
        icon: 'none'
      });
      return;
    }

    wx.showModal({
      title: '联系雇主',
      content: `联系电话：${this.data.job.employer.contactPhone}`,
      showCancel: true,
      cancelText: '取消',
      confirmText: '拨打',
      success: (res) => {
        if (res.confirm) {
          wx.makePhoneCall({
            phoneNumber: this.data.job.employer.contactPhone
          });
        }
      }
    });
  },

  // 分享岗位
  onShareAppMessage() {
    return {
      title: `${this.data.job?.title} - ${this.data.job?.company}`,
      path: `/pages/job-detail/job-detail?id=${this.data.jobId}`,
      imageUrl: '/images/share-job.png'
    };
  },

  // 显示错误信息
  showError(message) {
    wx.showToast({
      title: message,
      icon: 'none'
    });
    setTimeout(() => {
      wx.navigateBack();
    }, 1500);
  },

  // 格式化薪资
  formatSalary(job) {
    if (!job) return '';
    const { minSalary, maxSalary, salaryType } = job;
    let unit = '';
    switch (salaryType) {
      case 'HOURLY': unit = '/时'; break;
      case 'DAILY': unit = '/天'; break;
      case 'MONTHLY': unit = '/月'; break;
      default: unit = '';
    }
    
    if (minSalary === maxSalary) {
      return `${minSalary}元${unit}`;
    }
    return `${minSalary}-${maxSalary}元${unit}`;
  },

  // 格式化岗位类型
  formatJobType(type) {
    const typeMap = {
      'FULL_TIME': '全职',
      'PART_TIME': '兼职',
      'TEMPORARY': '临时工',
      'INTERNSHIP': '实习'
    };
    return typeMap[type] || type;
  },

  // 获取申请状态文本
  getApplicationStatusText(status) {
    const statusMap = {
      'PENDING': '待处理',
      'ACCEPTED': '已接受',
      'REJECTED': '已拒绝',
      'COMPLETED': '已完成'
    };
    return statusMap[status] || status;
  }
});
